package org.hugh.space.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hugh.space.utils.SetupBean;


public class InitFilter  extends AbstractFilter implements Filter {

	private static final String SETUP_URL = "/setup";
    private static final String HOT_CRON_URL = "/hotCron";
    private static final String RESET_URL = "/reset";
    
    public InitFilter() {
    	super();
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, 
    		FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        String url = httpRequest.getServletPath();
        if (url.equals(SETUP_URL)) {
            SetupBean setupBean = (SetupBean)getSpringBean("setupBean");
        	setupBean.setup();
        	httpResponse.sendRedirect("/");
        	return;
        }
        if (url.equals(RESET_URL)) {
            SetupBean setupBean = (SetupBean)getSpringBean("setupBean");
            setupBean.clear();
        	setupBean.setup();
        	httpResponse.sendRedirect("/");
        	return;
        }
        if (url.equals(HOT_CRON_URL)) {
        	writeContent(httpResponse, "<h4>OK</h4>");
        	return;
        }
        chain.doFilter(request, response);
    }
    
    private void writeContent(HttpServletResponse response, String content)
    		throws IOException {
    	response.setContentType("text/html");
    	response.setCharacterEncoding("UTF-8");
    	response.getWriter().append("<html><body>" + content + "</body></html>");
    }
    
}
